/*
 * Copyright 2014 Semidata. All rights reserved.
 */
package com.semidata.rtd.engine.main;


import com.semidata.rtd.core.service.Service;
import com.semidata.rtd.core.service.ServiceManager;
import com.semidata.rtd.engine.executor.TaskExecutor;
import com.semidata.rtd.engine.job.Job;

/**
 * @author shewei@semidata.com, She Wei
 *
 */
public class TestService implements Service {

	private static TaskExecutor executor = ServiceManager.getService(TaskExecutor.class);
	
	private Thread[] threads;
	private int threadNum;
	private boolean quit = false;

	private int concurrentNum;
	
	public TestService(int threadNum, int concurrentNum) {
		this.threadNum = threadNum;
		this.concurrentNum = concurrentNum;
	}

	@Override
	public void start() {
		threads = new Thread[threadNum];

		for (int i = 0; i < threadNum; i++) {

			threads[i] = new Thread(new Runnable() {

				@Override
				public void run() {
					test();
				}

			});
			threads[i].start();
		}
	}

	@Override
	public void stop() {
		System.out.println("stop test service...");
		quit = true;
		for (int i = 0; i < threadNum; i++) {
			try {
	            threads[i].join();
            } catch (InterruptedException e) {
	            e.printStackTrace();
            }
		}
		System.out.println("stop test service...ok");
	}
	
	private void test() {
		
		while (!quit) {
			
			for (int i = 0; i < concurrentNum; i++) {
				Job job = new TestJob(executor);
				job.start();
			}
			
			try {
	            Thread.sleep((long) (2 + Math.random() * 10));
            } catch (InterruptedException e) {
	            e.printStackTrace();
            }
		}
		
	}

}
